package com.bow.algorithm.java;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author vv
 * @since 2020/2/2
 */
public class StreamDemo {

	public static void main(String[] args) {
		List<Item> items = new ArrayList<>();
		items.add(new Item("v1", 20));
		items.add(new Item("v1", 20));
		items.add(new Item("v2", 20));
		items.add(new Item("v3", 22));
		items.add(new Item("v4", 23));

		List<Item> result = items.stream().filter(item -> item.getAge() < 23).distinct()
				.sorted(Comparator.comparingInt(Item::getAge).reversed()).collect(Collectors.toList());
		result.forEach(item -> {
			System.out.println(item.getName() + "," + item.getAge());
		});

        Map<Integer, List<Item>> rMap = items.stream().collect(Collectors.groupingBy(Item::getAge));
        rMap.forEach((key, value) -> {
            System.out.println(key+" "+value.size());
        });
	}
}

class Item {

	public Item(String name, int age) {
		this.name = name;
		this.age = age;
	}

	private String name;

	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;
		Item item = (Item) o;
		return age == item.age && Objects.equals(name, item.name);
	}

	@Override
	public int hashCode() {
		return Objects.hash(name, age);
	}
}
